package com.woniuxy.portal.controller;

import com.woniuxy.comon.RedisConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/email")
@Api(tags = "邮件服务")
public class EmailController {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation("发送邮件")
    @GetMapping("/send")
    public ResponseEntity<String> sendEmail(String address) {
        String code = RandomStringUtils.randomNumeric(4);
        String context = "注册的验证码是：" + code + ", 该验证码15分钟之内有效！";

        Map<String, Object> emailData = new HashMap<>();
        emailData.put("from", from);
        emailData.put("to", address);
        emailData.put("subject", "蜗牛书城：注册验证码");
        emailData.put("content", context);

        rabbitTemplate.convertAndSend("email.queue", emailData);

        //将数据存储在Redis中,时间设置为15分钟，邮箱地址是键
        stringRedisTemplate.opsForValue().set(RedisConst.EMAIL_ADDRESS_PREFIX + address, code, 15, TimeUnit.MINUTES);

        return ResponseEntity.ok("验证码已经发送到" + address + "邮箱，请去查收！");
    }
}